package com.huike.test;

import io.jsonwebtoken.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 测试JWT的使用
 */
public class JWT {
    public static void main(String[] args) throws InterruptedException {
        //获取JWT的构造方法

        JwtBuilder builder = Jwts.builder();
        String signature = "itheima";
        String token = builder.
                //封装header属性
                        setHeaderParam("typ", "JWT").
                setHeaderParam("alg", "HS256").
                //封装payload里的信息 使用claim方法
                        claim("name", "zhangsan")
                .claim("age", 18)
                .claim("sex", "男")
                .claim("username", "zs")
                //在payLoad中设置一个超时时间  秒   分 时
                .setExpiration(new Date(System.currentTimeMillis() + Long.valueOf(1000 * 10)))
                .setId("20184103044")
                //构造signature部分
                .signWith(SignatureAlgorithm.HS256, signature)
                //构造我们的签名 调用compact方法
                .compact();
        //输出构造的jwt
        System.out.println(token);//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJhZ2UiOjE4LCJzZXgiOiLnlLciLCJ1c2VybmFtZSI6InpzIiwiZXhwIjoxNjY1NTcwMTk0LCJqdGkiOiIyMDE4NDEwMzA0NCJ9.phS6ieTU9GcdDhYMFfsYclU0dbg1n654G7Ke1_KndqU

//让线程睡眠12秒
     //   Thread.sleep(1000 * 12);
//String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJhZ2UiOjE4LCJzZXgiOiLnlLciLCJ1c2VybmFtZSI6InpzIiwiZXhwIjoxNjY1NTcwMTk0LCJqdGkiOiIyMDE4NDEwMzA0NCJ9.phS6ieTU9GcdDhYMFfsYclU0dbg1n654G7Ke1_KndqU";
        //获取Jwt的解析对象
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
        Claims body = claimsJws.getBody();

        //获取name
        System.out.println(body.get("name"));
        //获取性别
        System.out.println(body.get("sex"));
        //获取用户名
        System.out.println(body.get("username"));
        //获取id
        System.out.println(body.getId());
        //获取有效期-截止时间
        System.out.println(body.getSubject());
        System.out.println(body.getExpiration());
    }
}
